package com.uyayo.oms.notepad.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.pagehelper.pojo.PageResult;
import com.uyayo.oms.notepad.vo.NoteInfoVO;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.notepad.entity.Note;
import com.uyayo.notepad.model.NoteCondition;
import com.uyayo.notepad.service.NoteService;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.service.MemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 
 * Title: GroupController
 * Description:会员组的控制器
 * Company: www.uyayo.com
 *
 * @author 优雅哟.胡逢君
 * @date 2015-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/notepad/note")
public class NoteController {

	private final NoteService noteService;

	private final ParamBiz paramBiz;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final MemberService memberService;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	public NoteController(ParamBiz paramBiz, NoteService noteService, MessageSource messageSource, DozerBeanMapper dozerBeanMapper, MemberService memberService) {
		this.paramBiz = paramBiz;
		this.noteService = noteService;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
		this.memberService = memberService;
	}

	@RequestMapping(value="index",method=RequestMethod.GET)
	@MethodName(value="记事管理->记事本管理")
	@RequiresPermissions("notepad:note:index")
	public String index() throws Exception {
		return paramBiz.getManagerTemplatesPrefix()+"notepad/note/index";
	}
	
	@ResponseBody
	@RequestMapping(value="query",method=RequestMethod.GET)
	@MethodName(value="记事管理->记事本管理->查询列表",type=2)
	@RequiresPermissions("notepad:note:query")
	public PageResult<Note> query(@RequestParam(value = "offset",required = false, defaultValue = "1") Integer start, //第多少行之后开始
								  @RequestParam(value = "limit", required = false, defaultValue = "10") Integer pageSize,
								  String sort, String order, HttpServletRequest request,String username, NoteCondition noteCondition) throws Exception {
		PageBean<Note> pageBean=new PageBean<>();
		try {
			pageBean.setPageCurrent((start / pageSize) + 1);
			pageBean.setPageSize(pageSize);
			pageBean.setOrderField(sort);
			pageBean.setOrderDirection(order);
			if(!StringUtils.isEmpty(username)){
				Member member = memberService.getMemberByUsername(username);
				if(member==null){
					String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
					logger.warn(message);
					PageResult<Note> pageResult = new PageResult<>();
					pageResult.setRows(pageBean.getList());
					pageResult.setTotal(pageBean.getTotalCount());
					return pageResult;
				}
				noteCondition.setMemberId(member.getId());
			}
			pageBean = noteService.selectNoteByPaging(pageBean,noteCondition);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		PageResult<Note> pageResult = new PageResult<>();
		pageResult.setRows(pageBean.getList());
		pageResult.setTotal(pageBean.getTotalCount());
		return pageResult;
		
	}
	
	/**
	 * 进入添加页面
	 * @param modelAndView ModelAndView
	 * @return ModelAndView
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	@RequiresPermissions("notepad:note:create")
	public ModelAndView add(ModelAndView modelAndView) {
		
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/note/add");
		return modelAndView;
	}
	
	/**
	 * 新建一个服务器记录
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@RequiresPermissions("notepad:note:create")
	@MethodName(value="记事管理->记事本管理->保存",type=2)
	synchronized public Result add(HttpServletRequest request, @Validated NoteInfoVO noteVO , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(noteVO.getUsername());
			if(Objects.isNull(member)){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			Note note = dozerBeanMapper.map(noteVO,Note.class);
			note.setMemberId(member.getId());
			note.setCreateTime(new Date());
			note.setCreateBy(sysUser.getLoginname());
			noteService.saveNote(note);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}
	
	/**
	 * 进入服务器记录查看页面
	 */
	@RequestMapping(value = "view", method = RequestMethod.GET)
	@MethodName(value="记事管理->记事本管理->查看",type=2)
	@RequiresPermissions("notepad:note:view")
	public ModelAndView show(ModelAndView modelAndView,HttpServletRequest request,Long id) {
		try {
			Note note = noteService.selectByKey(id);
			Member member = memberService.getMemberById(note.getMemberId());
			NoteInfoVO noteInfoVO = dozerBeanMapper.map(note,NoteInfoVO.class);
			noteInfoVO.setUsername(member.getUsername());
			modelAndView.addObject("note",noteInfoVO);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/note/view");
		return modelAndView;
	}

	/**
	 * 进入角色修改页面
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	@RequiresPermissions("notepad:note:update")
	public ModelAndView update(ModelAndView modelAndView,HttpServletRequest request,Long id) {

		try {
			Note note = noteService.selectByKey(id);
			Member member = memberService.getMemberById(note.getMemberId());
			NoteInfoVO noteInfoVO = dozerBeanMapper.map(note,NoteInfoVO.class);
			noteInfoVO.setUsername(member.getUsername());
			modelAndView.addObject("note",noteInfoVO);
			modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/note/edit");
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
		}
		return modelAndView;
	}
	
	/**
	 * 修改一个服务器记录
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@RequiresPermissions("notepad:note:update")
	@MethodName(value="记事管理->记事本管理->修改",type=2)
	synchronized public Result update(HttpServletRequest request,@Validated NoteInfoVO noteVO , Errors errors) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
		    }
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(noteVO.getUsername());
			if(Objects.isNull(member)){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			Note note = dozerBeanMapper.map(noteVO,Note.class);
			note.setMemberId(member.getId());
			note.setUpdateTime(new Date());
			note.setUpdateBy(sysUser.getLoginname());
			noteService.updateNote(note);
		} catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}

	/**
	 * 删除记录
	 */
	@ResponseBody
	@RequiresPermissions("notepad:note:delete")
	@RequestMapping(value="delete",method=RequestMethod.DELETE)
	@MethodName(value="记事管理->记事本管理->删除",type=2)
	public Result delete(HttpServletRequest request, Long id) {
		try {
			if (id==null) {
				String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
			}
			int deleteCount = noteService.delete(id);
			if(deleteCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.DELETE_FAIL.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.DELETE_FAIL.code(),message);
			}
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
		String message = messageSource.getMessage(ResultMsgEnum.DELETE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.DELETE_SUCCESS.code(),message);

	}
}
